package cumeo89.chii.client.entry.editor;

import java.util.ArrayList;
import java.util.Collection;

import com.google.gwt.user.client.ui.SuggestOracle;
import com.google.gwt.user.client.ui.SuggestOracle.Suggestion;

import cumeo89.chii.client.Chii;
import cumeo89.chii.client.util.AsyncCallback;

class CategoryEditor extends SuggestEditor {

	public CategoryEditor() {
		initEditor(new CategorySuggestOracle());
	}

	private class CategorySuggestOracle extends SuggestOracle {

		private boolean busy = false;
		private Request waitingRequest = null;
		private Callback waitingCallback = null;

		private void setBusy(boolean busy) {
			this.busy = busy;
			if (!busy && waitingCallback != null) {
				Request request = waitingRequest;
				waitingRequest = null;
				Callback callback = waitingCallback;
				waitingCallback = null;
				requestSuggestions(request, callback);
			}
		}

		@Override
		public void requestSuggestions(final Request request,
				final Callback callback) {
			if (busy) {
				waitingRequest = request;
				waitingCallback = callback;
				return;
			}

			if (request.getQuery().length() < 3) {
				// empty response
				callback.onSuggestionsReady(request, new Response(
						new ArrayList<Suggestion>()));
				return;
			}

			setBusy(true);
			Chii.get().getMediaWiki().getCategories(request.getQuery(),
					new AsyncCallback<String[]>() {

						public void onFailure(Throwable caught) {
							setBusy(false);
						}

						public void onSuccess(String[] result) {
							try {
								Collection<Suggestion> suggestions = new ArrayList<Suggestion>();
								for (int i = 0; i < result.length; i++) {
									suggestions.add(new CategorySuggestion(
											result[i]));
								}
								callback.onSuggestionsReady(request,
										new Response(suggestions));
							} finally {
								setBusy(false);
							}
						}

					});
		}

	}

	private static class CategorySuggestion implements Suggestion {

		private String categoryName;

		public CategorySuggestion(String categoryName) {
			this.categoryName = categoryName;
		}

		public String getDisplayString() {
			return categoryName;
		}

		public String getReplacementString() {
			return categoryName;
		}

	}

}
